﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using QSAspMvc.Models;

namespace QSAspMvc.Data
{
	/// <summary>
	/// An extremely basic, in session (gasp!), repository for products
	/// </summary>
	public class SessionProductRepository : IProductRepository
	{
		const string PRODUCT__REPOSITORY_KEY = "ProductRepository";

		/// <summary>
		/// Initializes a new instance of the SessionProductRepository class.
		/// </summary>
		public SessionProductRepository()
		{
		}

		#region IProductRepository Members

		public IQueryable<Product> GetProducts()
		{
			return Products.AsQueryable();
		}

		public Product GetProduct(int id)
		{
			return Products.SingleOrDefault(x => x.ProductId == id);
		}

		public void SaveProduct(Product product)
		{
			// try to remove old product
			Products.RemoveAll(x => x.ProductId == product.ProductId);
			// save
			Products.Add(product);
		}

		#endregion


		private List<Product> Products
		{
			get
			{
				if (HttpContext.Current.Session[PRODUCT__REPOSITORY_KEY] == null)
					HttpContext.Current.Session[PRODUCT__REPOSITORY_KEY] = new List<Product>();

				return (List<Product>)HttpContext.Current.Session[PRODUCT__REPOSITORY_KEY];
			}
			set
			{
				if (HttpContext.Current.Session[PRODUCT__REPOSITORY_KEY] == null)
					HttpContext.Current.Session[PRODUCT__REPOSITORY_KEY] = new List<Product>();

				HttpContext.Current.Session[PRODUCT__REPOSITORY_KEY] = value;
			}
		}
	}
}
